import json
import base64
import requests
import numpy as np
from scipy.io import wavfile


parameter1 = {
    "mode": "",  # 模式：文本合成 '#synth_text' 或 拼音合成 '#synth_pinyin'
    "text": "",  # 文本
    "pinyin": "",  # 拼音
    "gender": "",  # 常规语音性别
    "speaker_id": "",  # 常规语音id
    "synthesizer_id": "2",
    "vocoder_id": "6",
    "type": "wav",
    "speed": 1,
    "volume": 1
}

parameter2 = {
    'speaker_name': '',  # 说话人id, 必须上传
    'text': '',  # 文本或拼音
    'is_pinyin': False,  # text是否为拼音
    'wav': ''  # base64.b64encode()
}


def tts(text, gender, speaker_id, is_text=True, is_preview=False):
    url = 'http://111.230.90.48:9006/tts'
    if is_text:
        parameter1['text'] = text
        parameter1['mode'] = '#synth_text'
    else:
        parameter1['pinyin'] = text
        parameter1['mode'] = '#synth_pinyin'
    parameter1['gender'] = gender
    parameter1['speaker_id'] = speaker_id
    # 如果文本较长，timeout要设定大一点
    response = requests.post(url, json=parameter1, timeout=500)
    # response = requests.post(url, data=json.dumps(parameter1), timeout=500)
    # print(response.text)
    # print(response.status_code)

    if response.status_code == 200:
        data = response.json()
        text = data['text']  # 文本
        pinyin = data['pinyin']  # 文本转换的拼音
        if is_preview:
            return [text, pinyin]
        src_0 = data['src_0']
        wav_url = 'http://111.230.90.48:9006/' + src_0  # 合成的音频文件地址
        return wav_url
    # 多音字问题 临时解决方案：
    # 1. response 有反馈 text 和 pinyin， 可以给用户提供拼音修改功能
    # 2. 将修改后的拼音 放入parameter 中的 'pinyin', 并将 'mode' 改成 '#synth_pinyin'
    # 例如：parameter['pinyin']='di4 yi1 hang2 .' parameter[mode]='#synth_pinyin'
    # 3. 拼音模式重新合成


def ttsClone(speaker_id, is_pinyin=False, text='', save_path='', wav_path='', first_try=False):
    # wav_path = r"D:/Desktop/4.wav"
    # wav_path = r"/home/chenyiting/Code/Voice_clone_for_student/models/reference_audios/0001/0001_000051.wav"
    url = 'http://10.249.40.160:9006/tts'

    if first_try:
        with open(wav_path, 'rb') as f:
            wav = f.read()
        data = {
            'speaker_name': speaker_id,
            'wav': base64.b64encode(wav)
        }
        requests.post(url, data=data)
    else:
        data = {
            'speaker_name': speaker_id,
            'text': text,
            'is_pinyin': is_pinyin
        }
        result = requests.post(url, data=data)
        synth_wav = np.array(result.json()['wav']).astype(np.int16)
        wavfile.write(save_path, 22050, synth_wav)
